package com.example.health.db

import android.content.Context
import com.example.health.bean.Contact
import java.util.*


class SQLiteUtil(context: Context) {
    val dBhelper = DBhelper(context, "contactInfo", 1)
    fun insertContact(contact: Contact) {
        if (!isHave(contact)) {
            val writableDatabase = dBhelper.writableDatabase
            var sql = "insert into contactInfo (name, phone,contact_phone, address, iconurl) values ('${contact.name}', '${contact.phone}','${contact.contact_phone}','','')"
            writableDatabase.execSQL(sql)
            writableDatabase.close()
        }
    }

    private fun isHave(contact: Contact): Boolean {
        var sql = "select * from contactInfo where phone = ? and contact_phone = ?"
        val readableDatabase = dBhelper.readableDatabase
        val array = arrayOf(contact.phone, contact.contact_phone)
        val rawQuery = readableDatabase.rawQuery(sql, array)
        if (rawQuery.moveToNext()) {
            rawQuery.close()
            readableDatabase.close()
            return true
        }
        return false
    }

    fun getContactList(phone:String): ArrayList<Contact>? {
        val arrayList = ArrayList<Contact>()
        val readableDatabase = dBhelper.readableDatabase
        val array = arrayOf(phone)
        var sql = "select * from contactInfo where phone = ?"
        val cursor = readableDatabase.rawQuery(sql,array)
        while (cursor.moveToNext()) {
            val contact = Contact()
            val name: String = cursor.getString(cursor.getColumnIndex("name"))
            val contact_phone: String = cursor.getString(cursor.getColumnIndex("contact_phone"))
            contact.phone = phone
            contact.contact_phone = contact_phone
            contact.name = name
            arrayList.add(contact)
        }
        return arrayList
    }
}